///  author : douyu
///  date : 2023/12/20 17:28
///  description : left_slider_menu

import 'package:cached_network_image/cached_network_image.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_android_tv/Routes/Event/event_bus_type.dart';
import 'package:flutter_android_tv/Routes/Model/source_category_model.dart';
import 'package:flutter_android_tv/Routes/Notifier/source_change_notifier.dart';
import 'package:flutter_android_tv/common_tool/zjLogFile.dart';
import 'package:provider/provider.dart';
import '../part_refresh_widget/single_data_line.dart';
import 'package:flutter_android_tv/Routes/Model/source_info_model.dart';

import 'dart:ui';

final height =  window.physicalSize.height;

class ZJLeftSlideMenu extends StatefulWidget {

  final Function(int selectIndex) pressCallback;

  final bool isTV;

  const ZJLeftSlideMenu({super.key, required this.pressCallback,this.isTV = false});

  @override
  State<ZJLeftSlideMenu> createState() => ZJLeftSlideMenuState();
}

class ZJLeftSlideMenuState extends State<ZJLeftSlideMenu> with SingleTickerProviderStateMixin, MultDataLine {

  final FocusScopeNode _categoryNode = FocusScopeNode();
  final FocusScopeNode _secondaryNode = FocusScopeNode();

  final _firstListController = ScrollController();

  final _secondaryListController = ScrollController();
  int categoryIndex = 0;

  ///设置动画参数
  late final AnimationController _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 250))..repeat(reverse: true);
  late final Animation<Offset> _startAnimation = Tween<Offset>(
      begin: Offset.zero,
      end: const Offset(-1, 0)
  )
      .animate(CurvedAnimation(parent: _controller, curve: Curves.linear));

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //初始化隐藏slide
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      FocusScope.of(context).canRequestFocus;
      FocusScope.of(context).requestFocus(_secondaryNode);
    });

    changeSliderAnimation(false);

    /// 侧边栏是否展示
    eventBus.on<SlideShowChangeEvent>().listen((event) {
      changeSliderAnimation(event.isShowSlide);
    });

    /// 侧边栏是否展示
    eventBus.on<SlideChangeWithIndexEvent>().listen((event) {
      categoryIndex = event.categoryIndex;
      scrollToSelectIndex(categoryIndex,event.secondaryIndex);
    });

    //监听事件 通知list修改当前位置信息 切换当前选中Focus
    eventBus.on<ChangeSourceMenuEvent>().listen((event) {
      //判断对应的操作展示
      _changeMenuAction(event.isChooseCategory);
    });
  }


  /// 菜单切换逻辑处理
  void _changeMenuAction(bool isCategory){
    FocusScope.of(context).canRequestFocus;
    if(isCategory){
      FocusScope.of(context).requestFocus(_categoryNode);
    }else{
      FocusScope.of(context).requestFocus(_secondaryNode);
    }
    zjLog("当前展示category:${_categoryNode.isFirstFocus},secondary:${_secondaryNode.isFirstFocus}",);
  }

  /// 操作事件处理
  void scrollToSelectIndex(int categoryIndex, int secondaryIndex) {
    //选中了之后 UI样式修改 开始回调给外面执行拉流操作
    // selectIndex = index;
    if (widget.isTV){
      if(_categoryNode.isFirstFocus){
        _firstListController.animateTo((60 * categoryIndex).toDouble(), duration: const Duration(milliseconds: 250), curve: Curves.linearToEaseOut);
      }else{
        _secondaryListController.animateTo((60 * secondaryIndex).toDouble(), duration: const Duration(microseconds: 250), curve: Curves.linearToEaseOut);
      }
    }
  }

  void changeSliderAnimation(bool isShow){
    isShow ? _controller.reverse() : _controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    /// MediaQuery移除ListView顶部
    return MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child:  widget.isTV ? SlideTransition(
          position: _startAnimation,
          child: ClipRect(
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 10.0,sigmaY: 10.0),
              child: Container(
                height: height,
                width: 400,
                decoration: BoxDecoration(
                    color:Colors.white.withAlpha(100),
                    boxShadow: const [
                      BoxShadow(
                          color: Colors.black12,
                          offset: Offset(5, 5),
                          blurRadius: 15,
                          spreadRadius: 1
                      )
                    ]
                ),
                child: _showPhoneWidget(),
              ),
            ),
          ),
        ) : _showPhoneWidget(),
    );
  }


  Widget _showPhoneWidget(){
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                flex: 1,
                child: FocusScope(
                  node: _categoryNode,
                  autofocus: false,
                  child: Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 1)
                    ),
                    child: Consumer<IPTVCategoryProvider>(builder: (context,IPTVCategoryProvider sourceProvider, Widget? child){
                      return ListView.builder(
                          itemExtent: 60,
                          controller: _firstListController,
                          itemCount: sourceProvider.categorySources.length,
                          itemBuilder: (BuildContext context, int index){
                            return Selector<IPTVCategoryProvider, SourceCategoryModel>(
                                selector: (context, provider) => provider.categorySources[index],
                                builder: (context, data, child){
                                  return GestureDetector(
                                    onTap: (){
                                      ///修改当前选中的数据
                                      Provider.of<IPTVCategoryProvider>(context,listen: false).gestureChangeSlideIndex(index,0);
                                      eventBus.fire(SlideChangeWithIndexEvent(index, 0));
                                      widget.pressCallback(index);
                                    },
                                    child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                                        alignment: Alignment.centerLeft,
                                        decoration: data.isChoose ? BoxDecoration(
                                            color: Colors.blue,
                                            boxShadow: [
                                              BoxShadow(
                                                  color: Colors.blue.withOpacity(0.5),
                                                  offset: const Offset(2.0, 2.0),
                                                  blurRadius: 3,
                                                  spreadRadius: 1.0
                                              ),
                                            ]
                                        ) : const BoxDecoration(
                                            color: Colors.transparent
                                        ),
                                        child: Text(
                                            data.name,
                                            style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20)
                                        ),
                                    )
                                  );
                                });
                          });
                    }),
                  ),
                ),
              ),
              Expanded(
                flex: 3,
                child: FocusScope(
                  node: _secondaryNode,
                  autofocus: true,
                  child: Container(
                    decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 1)
                    ),
                    child: Consumer<IPTVSecondarySourceProvider>(builder: (context,IPTVSecondarySourceProvider sourceProvider, Widget? child){
                      return ListView.builder(
                        itemExtent: 60,
                        controller: _secondaryListController,
                        itemCount: sourceProvider.categoryModel.sources.length,
                        itemBuilder: (BuildContext context, int index){
                            return Selector<IPTVSecondarySourceProvider, SourceInfoModel>(
                                selector: (context, provider) => provider.categoryModel.sources[index],
                                builder: (context, data, child){
                                  return GestureDetector(
                                    onTap: (){
                                      ///修改当前选中的数据
                                      Provider.of<IPTVCategoryProvider>(context,listen: false).gestureChangeSlideIndex(categoryIndex, index);
                                      eventBus.fire(SlideChangeWithIndexEvent(categoryIndex,index));
                                      widget.pressCallback(index);
                                    },
                                    child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                                        alignment: Alignment.centerLeft,
                                        decoration: data.isChoose ? BoxDecoration(
                                            color: Colors.blue,
                                            boxShadow: [
                                              BoxShadow(
                                                  color: Colors.blue.withOpacity(0.5),
                                                  offset: const Offset(2.0, 2.0),
                                                  blurRadius: 3,
                                                  spreadRadius: 1.0
                                              ),
                                            ]
                                        ) : const BoxDecoration(
                                            color: Colors.transparent
                                        ),
                                        child: Row(
                                          children: [
                                            CachedNetworkImage(
                                              imageUrl: "https://zhangjiang1203.github.io/images/TVLogo/${data.name}.png",
                                              width: 80,
                                              fit: BoxFit.fitHeight,
                                            ),
                                            const Padding(padding: EdgeInsets.only(left: 10)),
                                            Text(
                                                data.name,
                                                style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20)
                                            ),
                                          ],
                                        )
                                    ),
                                  );
                                });
                          });
                    }),
                  )
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _controller.dispose();
    _firstListController.dispose();
    _secondaryListController.dispose();
  }
}
